<template>
  <div class="px-20 pb-10">
    <!-- 基于element-plus创建一个表单，包含字段 一级指标，二级指标，考核频率，指标说明及工作内容、工作要求，指标单位，指标值，考核评分标准，分值权重，考核人，被考核人部门，被考核人姓名，被考核人职务，被考核人岗位，技分方式  -->
    <el-form
      class="mt-4"
      :model="form"
      ref="formRef"
      destroy-on-close
      :rules="rules"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="目标财年：" prop="targetYear">
            <el-date-picker
              v-model="form.targetYear"
              type="year"
              style="width: 100%"
              :disabled="flag == 'update'"
              placeholder="请选择目标财年"
              :clearable="false"
              value-format="YYYY"
              format="YYYY"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标金额：" prop="targetValue">
            <el-input
              :disabled="flag == 'update'"
              v-model="form.targetValue"
              placeholder="请输入年度目标金额"
            >
              <template #append>
                <el-select
                  :disabled="flag == 'update'"
                  v-model="form.targetUnit"
                  style="width: 80px"
                  placeholder="单位"
                >
                  <el-option label="万元" value="万元"></el-option>
                  <el-option label="元" value="元"></el-option>
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="业务类型：" prop="targetBizSegmentArr">
            <el-tree-select
              class="w-full"
              :disabled="flag == 'update'"
              v-model="form.targetBizSegmentArr"
              @change="handleGetTableCol"
              placeholder="请选择业务分类"
              multiple
              check-strictly
              :data="businessTypeOption"
            />
            <!-- <el-select
              class="w-full"
              :disabled="flag == 'update'"
              v-model="form.targetBizSegmentArr"
              placeholder="业务类型"
              @change="handleGetTableCol"
            >
              <el-option
                v-for="dict in businessTypeOption"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标类型：" prop="targetType">
            <el-select
              class="w-full"
              :disabled="flag == 'update'"
              v-model="form.targetType"
              placeholder="目标类型"
            >
              <el-option
                v-for="dict in target_type"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标分类：" prop="targetClassification">
            <el-select
              class="w-full"
              :disabled="flag == 'update'"
              v-model="form.targetClassification"
              placeholder="目标分类"
            >
              <el-option
                v-for="dict in target_classification"
                :label="dict.label"
                :value="dict.value"
                :key="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="目标成员：" required>
            <div class="flex flex-col w-full">
              <div class="mb-2">
                <el-button type="primary" @click="selectAssessorUser"
                  >选择</el-button
                >
              </div>
              <div>
                <template v-if="assessorUserObj.length > 0">
                  <el-row v-for="(item, index) in assessorUserObj" :key="index">
                    <el-col :span="2">{{ item.label }}：</el-col>
                    <el-col :span="21">
                      <el-tag
                        v-for="tag in item.selectData"
                        :key="tag.itemValue"
                        class="mr-2 mb-2"
                        :type="tagType[index % 5]"
                      >
                        {{ tag.itemLabel }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </template>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <TitleName
          title="目标分解"
          class="py-2"
          icon="i-carbon-bookmark-filled"
        ></TitleName>
        <el-col :span="24">
          <avue-crud
            v-if="
              form.targetBizSegmentArr?.length > 0 &&
              assessorUserObj?.length > 0
            "
            ref="crudProduct"
            :option="crudOption"
            :data="form.sonlist"
            class="hide-required-asterisk"
          >
            <!-- <template #warehouse-header="{ column }">
              <span class="text-red pr-2">*</span
              ><span>{{ column.label }}</span>
            </template> -->
            <template #empty>
              <div>暂无数据</div>
            </template>
          </avue-crud>
          <!-- <el-row :gutter="10" class="flex items-center" style="overflow: auto">
            <el-col
              :span="6"
              class="mb-3"
              v-for="(item, index) in allocationList"
              :key="index"
            >
              <el-card class="box-card" shadow="never">
                <template #header>
                  <div class="flex items-center">
                    <div class="w-1/3 truncate">
                      <el-tooltip
                        effect="dark"
                        :content="item.itemLabel"
                        placement="top-start"
                      >
                        <span>
                          <span style="color: red">*</span>
                          {{ item.itemLabel }}
                        </span>
                      </el-tooltip>
                    </div>
                    <div class="w-2/3">
                      <el-input
                        type="number"
                        min="0"
                        placeholder="金额"
                        v-model="item.targetValue"
                      ></el-input>
                    </div>
                  </div>
                </template>
                <div>
                  <div class="inline-flex items-center mb-2">
                    <span class="w-35 text-gray-600">第一季度</span>
                    <el-input
                      type="number"
                      min="0"
                      placeholder="金额"
                      v-model="item.targetSeason1"
                    />
                  </div>
                  <div class="inline-flex items-center mb-2">
                    <span class="w-35 text-gray-600">第二季度</span>
                    <el-input
                      type="number"
                      min="0"
                      placeholder="金额"
                      v-model="item.targetSeason2"
                    />
                  </div>
                  <div class="inline-flex items-center mb-2">
                    <span class="w-35 text-gray-600">第三季度</span>
                    <el-input
                      type="number"
                      min="0"
                      placeholder="金额"
                      v-model="item.targetSeason3"
                    />
                  </div>
                  <div class="inline-flex items-center mb-2">
                    <span class="w-35 text-gray-600">第四季度</span>
                    <el-input
                      type="number"
                      min="0"
                      placeholder="金额"
                      v-model="item.targetSeason4"
                    />
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row> -->
        </el-col>

        <el-col :span="24" class="text-right">
          <el-button type="primary" @click="handleIndicatorSave"
            >保存</el-button
          >
          <el-button @click="dialogClose">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!--  select or tree 结构组件  -->
    <select-or-tree-dialog
      :dialog-param="selectOrTreeDialogParam"
      :tabsOptionsData="tabsOptionsData"
      @handleConfirm="handleConfirm"
    />
  </div>
</template>

<script setup name="AddOrUpdateTarget">
// 通用数据store
import useCommonStore from '@/store/modules/common'
import { getCurrentInstance } from 'vue'
import useUserStore from '@/store/modules/user'
import { maxDecimals } from '@/utils/validate'
import { saveOrUpdateSalestarget } from '@/api/salesManage/targetManage/targetAllocationBusiness'
import { getDept } from '@/api/rsgl/zzjg'
import {
  order_business_type, //业务类型
  businessTypeOption //业务类型树
} from '@/hooks/dict/order'

const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const emits = defineEmits(['dialogClose'])
const userStore = useUserStore()
const props = defineProps({
  // 1:新增 2:修改
  targetInfo: {
    type: String || Object,
    default: () => {
      return ''
    }
  },
  flag: {
    type: String,
    default: () => {
      return ''
    }
  }
})

const data = reactive({
  form: {
    memberType: userStore.user.orgId != 484 ? '1' : '0',
    targetYear: '',
    targetBizSegmentArr: [],
    targetType: '',
    targetUnit: '万元',
    sonlist: [],
    targetValue: ''
  },
  rules: {
    targetYear: [
      { required: true, message: '请选择年度目标金额', trigger: 'change' }
    ],
    targetValue: [
      {
        required: true,
        message: '请输入目标金额',
        trigger: 'change'
      },
      {
        validator: (rule, value, callback) => {
          maxDecimals(rule, value, callback, 6)
        }
      }
    ],
    targetBizSegmentArr: [
      {
        required: true,
        message: '请选择业务板块',
        trigger: 'change'
      }
    ],
    targetType: [
      {
        required: true,
        message: '请选择目标类型',
        trigger: 'change'
      }
    ],
    targetClassification: [
      {
        required: true,
        message: '请选择目标分类',
        trigger: 'change'
      }
    ]
  },
  selectOrTreeDialogParam: {},
  tabsOptionsData: [],

  tagType: {
    1: 'success',
    2: 'warning',
    3: 'danger',
    4: 'info',
    5: ''
  },
  confirmType: ''
})

const {
  form,
  rules,
  selectOrTreeDialogParam,
  tabsOptionsData,
  tagType,
  confirmType
} = toRefs(data)

const {
  target_type,
  target_classification //销售目标分类
} = proxy.useDict('target_type', 'target_classification')

// 考核人对象数组
const assessorUserObj = ref([])
const allocationList = ref([])
const flag = ref('')

watchEffect(() => {
  flag.value = props.flag
})

const dataTypeObj = {
  org: {
    label: '单位',
    name: 'org',
    selectData: []
  },
  dept: {
    label: '部门',
    name: 'dept',
    selectData: []
  },
  person: {
    label: '人员列表',
    name: 'person',
    selectData: []
  }
}

onMounted(() => {
  if (props.targetInfo !== '') {
    console.info(flag.value)
    getInfo(proxy.targetInfo)
  }
})

// 表格
const tableColumns = ref([])
const crudOption = ref({
  header: false,
  menu: false,
  menuFixed: 'right',
  delBtn: false,
  editBtn: false,
  addBtn: false,
  addRowBtn: false,
  saveBtn: false,
  cancelBtn: false,
  cellBtn: false,
  // searchBtn: false,
  refreshBtn: false,
  columnBtn: false,
  menuWidth: 100,
  border: true,
  column: computed(() => {
    return tableColumns.value
  })
  /*  [
    {
      label: '实际售价',
      prop: 'actualPrice',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '120',
      controls: false,
      rules: [
        {
          required: true,
          message: '请输入实际售价',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            maxDecimals(rule, value, callback, 6)
          }
        }
      ],
      cell: true
    }
  ] */
})
/**
 * 根据业务板块获取表头结构的change事件
 */
const handleGetTableCol = val => {
  tableColumns.value = [
    {
      label: '目标成员',
      prop: 'memberName',
      minWidth: '120'
    }
  ]
  // tableColumns.value = order_business_type.value.filter(
  //   item => form.value.targetBizSegmentArr.includes(item.value)
  //   // console.log(item)
  // )
  order_business_type.value.forEach(item => {
    let obj = { ...item }
    delete obj.children
    if (form.value.targetBizSegmentArr.includes(item.value)) {
      tableColumns.value.push({
        ...obj,
        prop: `key${item.dictCode}`,
        type: 'input',
        cell: true,
        minWidth: '120',
        rules: [
          {
            required: true,
            message: `请输入${item.label}金额`,
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ]
        //   label: '学历层次',
        //   prop: 'hierarchy',
        //   type: 'select',
        //   minWidth: '150',
        //   dicData: order_hierarchy,
      })
    }
  })
}

/**
 *根据info获取ids和names
 */
const getIdsAndNamesByInfo = (type, ids, names, data) => {
  if (ids != '' && ids != null) {
    let obj = {}
    let idsArr = ids.split(',')
    let namesArr = names.split(',')
    obj = JSON.parse(JSON.stringify(dataTypeObj[type]))
    idsArr.forEach((item, index) => {
      let o = {
        itemValue: item,
        itemLabel: namesArr[index]
      }
      if (type == 'person') {
        o.uuid = `U${item}`
      }
      obj.selectData.push(o)
    })
    data.push(obj)
  }
}

/**
 * @description: 获取指标详情
 */
const getInfo = targetInfo => {
  form.value = targetInfo
  let info = props.targetInfo
  Object.keys(form.value).forEach(key => {
    form.value[key] = info[key]
  })
  if (targetInfo.tableColumns != null) {
    tableColumns.value = targetInfo.tableColumns.map(item => {
      let obj = {}
      if (item.prop == 'memberName') {
        return item
      } else {
        obj = {
          ...item,
          rules: [
            {
              required: true,
              message: `请输入${item.label}金额`,
              trigger: 'blur'
            },
            {
              validator: (rule, value, callback) => {
                maxDecimals(rule, value, callback, 6)
              }
            }
          ]
        }
      }
      return obj
    })
  }
  if (targetInfo.sonlist != null) {
    let arr = []
    allocationList.value = targetInfo.sonlist.map(item => {
      return {
        $cellEdit: true,
        ...item
      }
    })
    form.value.sonlist = allocationList.value
    targetInfo.sonlist.forEach(item => {
      item.itemValue = item.memberId
      item.itemLabel = item.memberName
      switch (item.memberType) {
        // 单位
        case '1':
          dataTypeObj.org.selectData.push(item)
          break
        //     部门
        case '2':
          dataTypeObj.dept.selectData.push(item)
          break
        // 个人
        case '3':
          dataTypeObj.person.selectData.push(item)
          break
      }
    })
    Object.keys(dataTypeObj).forEach(key => {
      if (dataTypeObj[key].selectData.length > 0) {
        arr.push(dataTypeObj[key])
      }
    })
    assessorUserObj.value = arr
  }

  //考核人
  getIdsAndNamesByInfo(
    'dept',
    info.assessorDept,
    info.assessorDeptName,
    assessorUserObj.value
  )
  getIdsAndNamesByInfo(
    'duties',
    info.assessorDuties,
    info.assessorDutiesName,
    assessorUserObj.value
  )
  getIdsAndNamesByInfo(
    'post',
    info.assessorPost,
    info.assessorPostName,
    assessorUserObj.value
  )
  getIdsAndNamesByInfo(
    'person',
    info.assessorUser,
    info.assessorUserName,
    assessorUserObj.value
  )
}

/**
 * @description: 选择考核人
 */
const selectAssessorUser = () => {
  // 设置confirmType显示提交类型
  confirmType.value = 'assessorUser'
  //   tabs配置数组
  const tabsArr = [
    {
      label: '单位', //tab的label
      name: 'org', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'org', //数据类型
        multiple: true, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName', //树节点的label
        apiParams: {
          deptId: userStore.user.orgId != 484 ? userStore.user.orgId : ''
        }
      }
    },
    {
      label: '部门', //tab的label
      name: 'dept', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'dept', //数据类型
        multiple: true, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'deptId', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        treeLabelName: 'deptName', //树节点的label
        apiParams: {
          deptId: userStore.user.orgId != 484 ? userStore.user.orgId : ''
        }
      }
    },
    {
      label: '人员', //tab的label
      name: 'person', //tab的name
      component: 'CustomTree', //tab的组件
      componentOptions: {
        //组件的配置
        dataType: 'person', //数据类型
        multiple: true, //是否多选
        checkStrictly: false, //是否严格的父子关联
        nodeKey: 'uuid', //节点的key
        defaultCheckedKeys: [], //默认选中的节点
        apiParams: {
          deptId: userStore.user.orgId != 484 ? userStore.user.orgId : ''
        }
      }
    }
  ]
  switch (form.value.memberType) {
    // 所有
    case '0':
      tabsOptionsData.value = [tabsArr[0]]
      break
    // 单位
    case '1':
      tabsOptionsData.value = [tabsArr[1], tabsArr[2]]
      break
    //     部门
    case '2':
      tabsOptionsData.value = [tabsArr[2]]
      break
    // 个人
    case '3':
      return
  }
  // console.info('tabsOptionsData.value', tabsOptionsData.value)
  // 如果考核人对象数组有值
  if (assessorUserObj.value.length > 0) {
    //assessorUserObj,用find查找tabsOptionsData中name等于assessorUserObj的name的对象
    //将对象的componentOptions.defaultCheckedKeys设置为考核人对象数组中的selectData的itemValue集合
    //componentOptions的selectData等于assessorUserObj中的selectData
    assessorUserObj.value.forEach(item => {
      const obj = tabsOptionsData.value.find(tab => tab.name === item.name)
      obj.componentOptions.defaultCheckedKeys = item.selectData.map(
        item => item.itemValue
      )
      obj.componentOptions.selectData = item.selectData
    })
  }

  proxy.$nextTick(() => {
    // 弹窗标题
    selectOrTreeDialogParam.value.title = '请选择目标成员'
    // 弹窗是否发开
    selectOrTreeDialogParam.value.isDialog = true
    //  是否多选，如果结果要为单选，则组件componentOptions.multiple设置为false
    selectOrTreeDialogParam.value.resultMultiple = true
  })
}

/**
 * 考核人弹窗确定按钮
 */
const handleConfirm = result => {
  let resultArr = []
  // 如果result有值
  if (result.length > 0) {
    if (assessorUserObj.value.length > 0) {
      resultArr = result.map(item => {
        let obj = assessorUserObj.value.find(t => t.name == item.name)
        if (obj) {
          item.selectData = item.selectData.map(s => {
            let o = obj.selectData.find(t => t.itemValue == s.itemValue)
            if (o) {
              console.info('o', o)
              console.info('s', s)
              s = o
            }
            return s
          })
        }
        return item
      })
      console.info('resultArr', resultArr)
      assessorUserObj.value = resultArr
    } else {
      assessorUserObj.value = result
    }
  } else {
    // 设置考核人对象数组
    assessorUserObj.value = result
  }

  if (assessorUserObj.value) {
    let arr = []
    assessorUserObj.value.forEach(item => {
      let array = item.selectData.map(t => {
        t.memberType =
          item.name == 'org'
            ? '1'
            : item.name == 'dept'
            ? '2'
            : item.name == 'person'
            ? '3'
            : ''
        return t
      })
      arr = [...arr, ...array]
    })

    // 分配目标
    allocationList.value = arr
    let tableData = allocationList.value.map(item => {
      let obj = {
        $cellEdit: true,
        // ...item,
        id: item.memberId ? item.id : '',
        parentId: flag.value == 'add' ? '' : form.value.id,
        memberId: item.itemValue,
        memberName: item.itemLabel,
        memberType: item.memberType
      }
      switch (obj.memberType) {
        case '1':
          obj.roleType = 'dwld'
          obj.deptId = ''
          obj.orgId = item.itemValue
          break
        case '2':
          obj.roleType = 'bmld'
          obj.deptId = item.deptId
          obj.orgId = item.parentId
          break
        case '3':
          obj.deptId = item.deptId
          obj.orgId = ''
          break
      }
      return obj
    })
    // 获取差集
    let arrs = tableData.filter(
      item => !form.value.sonlist.some(t => t.memberId == item.memberId)
    )
    // 获取交集
    let arrs1 = form.value.sonlist.filter(item =>
      tableData.some(t => t.memberId == item.memberId)
    )
    form.value.sonlist = [...arrs1, ...arrs]
  }
}

const getValueByParams = (data, param, type) => {
  let result = ''

  let obj = data.find(item => item.name == param)
  if (obj) {
    if (type == 'ids') {
      result = obj.selectData
        .map(item => {
          return item.itemValue
        })
        .join(',')
    }
    if (type == 'labels') {
      result = obj.selectData
        .map(item => {
          return item.itemLabel
        })
        .join(',')
    }
  }

  return result
}

/**
 * 检查金额是否正确
 * @returns {boolean}
 */
const checkTargetSeason = () => {
  let count = 0
  // 使用正则表达式验证金额格式
  const regex = /^\d+(\.\d{1,2})?$/
  allocationList.value.forEach(item => {
    regex.test(item.targetValue) == true ? '' : count++
    item.targetSeason1 == '' || regex.test(item.targetSeason1) == true
      ? ''
      : count++
    item.targetSeason2 == '' || regex.test(item.targetSeason2) == true
      ? ''
      : count++
    item.targetSeason3 == '' || regex.test(item.targetSeason3) == true
      ? ''
      : count++
    item.targetSeason4 == '' || regex.test(item.targetSeason4) == true
      ? ''
      : count++
    if (
      parseFloat(item.targetSeason1) +
        parseFloat(item.targetSeason2) +
        parseFloat(item.targetSeason3) +
        parseFloat(item.targetSeason4) >
      parseFloat(item.targetValue)
    ) {
      count++
    }
  })
  return count > 0 ? true : false
}

// 弹窗保存事件
const handleIndicatorSave = () => {
  let subtableCheck = true
  let errMsg = []
  const { validate } = proxy.$refs.formRef
  validate(async (valid, msg) => {
    if (allocationList.value.length == 0) {
      proxy.$modal.msgWarning('请选择目标成员')
      return
    }
    // 产品信息信息校验
    let err = await proxy.$refs.crudProduct.validateCellForm()
    subtableCheck = subtableCheck ? !err : subtableCheck
    if (err) {
      // Object.keys(err).forEach(e => {
      //   ;`产品信息---${
      //     induEerrrr[e][0].message
      //   }`
      // })
      errMsg.push(`目标分解---${err[Object.keys(err)[0]][0].message}`)
    }
    subtableCheck = subtableCheck ? !err : subtableCheck
    if (msg) errMsg.unshift(`${msg[Object.keys(msg)[0]][0].message}`)
    if (valid && subtableCheck) {
      let params = JSON.parse(JSON.stringify(form.value))

      params.targetValue = params.targetValue * 1
      if (flag.value == 'add') {
        params.parentId = 0
        params.memberId =
          userStore.user.orgId != 484 ? userStore.user.orgId : 100
        params.memberName =
          userStore.user.orgId != 484
            ? userStore.user.orgIdCn
            : '福建航天信息科技有限公司'
        params.memberType = userStore.user.orgId != 484 ? '1' : '0'
        params.orgId = 484
        params.roleType = 'dwld'
      }

      // let sonlist = []
      // let keyNames = tableColumns.value.map(item => item.prop)
      // allocationList.value.forEach(item => {
      //   let obj = {
      //     $cellEdit: true,
      //     ...keyNames,
      //     ...item,
      //     id: item.memberId ? item.id : '',
      //     parentId: flag.value == 'add' ? '' : params.id,
      //     memberId: item.itemValue,
      //     memberName: item.itemLabel,
      //     memberType: item.memberType
      //   }
      //   switch (obj.memberType) {
      //     case '1':
      //       obj.roleType = 'dwld'
      //       obj.deptId = ''
      //       obj.orgId = item.itemValue
      //       break
      //     case '2':
      //       obj.roleType = 'bmld'
      //       obj.deptId = item.deptId
      //       obj.orgId = item.parentId
      //       break
      //     case '3':
      //       obj.deptId = item.deptId
      //       obj.orgId = ''
      //       break
      //   }
      //   sonlist.push(obj)
      // })
      // params.sonlist = sonlist
      params.tableColumns = tableColumns.value
      saveOrUpdateSalestarget(params).then(res => {
        if (res.code === 200) {
          proxy.$message.success('保存成功')
          emits('dialogClose', flag.value)
        }
      })
    } else {
      if (errMsg.length > 0) proxy.$modal.msgError(errMsg[0])
      // skipToError()
    }
  })
}

const dialogClose = () => {
  emits('dialogClose')
}

/**
 * 初始化
 */
const init = () => {}

init()
</script>

<style scoped lang="scss">
:deep(.box-card) {
  .el-card__header {
    padding: 7px 15px 7px !important;
    background: #f5f5f5;
  }
}
</style>
